# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import time

import logging

_logger = logging.getLogger(__name__)


class FapiaoPaper(models.Model):
    _inherit = "fp.fapiao.paper"

    def action_check(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'in_invoice'),
            ('state', 'in', ['confirmed', 'done']),

        ])

        return self.env['fp.fapiao.check'].find_by_fapiao(self2)


class FapiaoCheck(models.Model):
    _name = "fp.fapiao.check"
    _inherit = ['fp.fapiao.operate.mixin']
    _description = "Fapiao Check"
    # _order = 'sequence, name'

    fapiao_id = fields.Many2one(
        domain=[('type', 'in', ['in_invoice'])],
        help="被查验及查验结果数据")

    state = fields.Selection(
        selection_add=[
            # ('draft', 'Draft'),  # 初值
            ('recheck', 'recheck'),  # 查询完成 . 末状态  稳定状态
            # ('recheck2', 'recheck2'),  # 查询完成 . 末状态  稳定状态

            ('refunded', 'refunded'),  # 查询完成 . 末状态  稳定状态
            ('be_invalid', 'be_invalid'),  # 查询完成 . 末状态  稳定状态
            ('error', 'error'),  # 查询完成 . 末状态  稳定状态

            # ('done', 'done'),  # 查询完成 . 末状态  稳定状态

            # ('printing', 'Printing'),  # 打印中. 临时状态
            # ('printed', 'printed'),  # 已打印. 末状态  稳定状态
        ],
        string="查验控制", help="查验控制")

    api_check_id = fields.Many2one(
        'fp.api.check',
        string='Api Check',
        compute='_compute_api_check_id')

    @api.depends('company_id')
    def _compute_api_check_id(self):
        for one in self:
            api_company = self.env[
                'fp.api.check.company'].search_by_company(one.company_id)
            one.api_check_id = api_company.api_check_id

    def action_request(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('state', 'in', ['draft', 'recheck',
                             'done',  'refunded', 'be_invalid', 'error'])])

        # print('action_request', self, self2)

        if self2:
            for one in self2:
                one.state = 'doing'
                one.fapiao_id.state = 'doing'

            api_check_id = self2[0].api_check_id
            request_method = api_check_id._request_method_get()
            result = request_method(self2)

            for record in result:
                # print('action_request ok', record)

                # _logger.info("check fapiao return: %s" % record)

                one = self.browse(record['id'])
                one.state = record['state']

                values_for_fapiao = {}

                if record['state'] in ['error']:
                    values_for_fapiao['state'] = record['state']

                elif record['state'] in ['done', 'refunded', 'be_invalid']:

                    def partner_get(saler_or_buyer):
                        if saler_or_buyer == 'saler':
                            fapiao_name = record['saler_name']
                            tin = record['saler_tin']
                            address_phone = record['saler_address_phone']
                            bank_account = record['saler_bank_account']
                        else:
                            fapiao_name = record['buyer_name']
                            tin = record['buyer_tin']
                            address_phone = record['buyer_address_phone']
                            bank_account = record['buyer_bank_account']

                        partner = self.env['fp.partner'].lookup_for_in({
                            'fapiao_name': fapiao_name,
                            'tin': tin,
                            'address_phone': address_phone,
                            'bank_account': bank_account,

                        })

                        return partner.id

                    saler_id = partner_get('saler')
                    buyer_id = partner_get('buyer')

                    def product_get(line):
                        vat_product_code = line['vat_product_code']
                        vat_product_name = line['vat_product_name']
                        product_name = line['product_name']
                        product_spec = line['product_spec']
                        product_uom = line['product_uom']
                        price_unit = line['price_unit']

                        product = self.env['fp.product'].lookup_for_in({
                            'fp_partner_id': saler_id,
                            'vat_product_code': vat_product_code,
                            'vat_product_name': vat_product_name,
                            'product_name': product_name,
                            'product_spec': product_spec,
                            'product_uom': product_uom,
                            'price_unit': price_unit,
                        })

                        return product.id

                    def line_vals_get(index, line):
                        amount_total = line['amount_total']

                        line_type = index and amount_total < 0 and 'discount' or 'line'
                        is_discount = line_type == 'discount'

                        ref_line = is_discount and record['line_ids'][index-1] or line

                        return {
                            'name': line_type + ',' + str(1 + index),
                            'line_type': line_type,
                            'row_number_check': line['row_number'],
                            'row_number':  1 + index,
                            'ref_row_number': 1 + index - (is_discount and 1 or 0),
                            'product_id': product_get(ref_line),

                            'tax_ratio': line['tax_ratio'],
                            'quantity': line['quantity'],
                            'amount_untaxed': line['amount_untaxed'],
                            'amount_tax': line['amount_tax'],
                            'amount_total': line['amount_total'],

                            'price_untax': line['price_untax'],
                            'price_unit': line['price_unit'],

                        }

                    lines_in = [line_vals_get(
                        index, line) for index, line in enumerate(record['line_ids'])]

                    old_line_ids = one.fapiao_id.line_ids.ids

                    lines = []
                    for index, item in enumerate(lines_in):
                        old_ids_len = len(old_line_ids)
                        if index < old_ids_len:
                            op, lid = 1, old_line_ids[index]
                        else:
                            op, lid = 0, False

                        lines.append((op, lid,  item))

                    values_for_fapiao = {
                        # 'invoice_type': record['invoice_type'],
                        'taxmachine_code': record['taxmachine_code'],
                        # 'invoice_code': record.get('invoice_code'),
                        # 'invoice_number': record.get('invoice_number'),
                        'check_code': record['check_code'],

                        'saler_id': saler_id,
                        'buyer_id': buyer_id,

                        'note': record['note'],

                        # 'payee_name': record['payee_name'],
                        # 'checker_name': record['checker_name'],
                        # 'drawer_name': record['drawer_name'],

                        # 'date_fapiao': record['date_fapiao'],

                        'amount_untaxed': record['amount_untaxed'],
                        'amount_tax': record['amount_tax'],
                        'amount_total': record['amount_total'],
                        'line_ids': lines,
                    }

                    values_for_fapiao['state'] = record['state']

                print('action_request to write ', values_for_fapiao)

                if values_for_fapiao:
                    pass
                    one.fapiao_id.write(values_for_fapiao)


values_for_fapiao_return = {
    'taxmachine_code': '661619946800', 'check_code': '56183922060040110881',
    'saler_id': 1, 'buyer_id': 2, 'note': '订单号:229485836626',
    'amount_untaxed': 76.06, 'amount_tax': 9.49, 'amount_total': 85.55,
    'line_ids': [
        (0, False, {
            'line_type': 'line', 'row_number_check': 1, 'row_number': 1, 'ref_row_number': 1,
            'product_id': 1, 'tax_ratio': 13.0,
            'quantity': 5.0, 'amount_untaxed': 199.12, 'amount_tax': 25.88, 'amount_total': 225.0,
            'price_untax': 39.82300885, 'price_unit': 45.0}),
        (0, False, {
            'line_type': 'discount', 'row_number_check': 2, 'row_number': 2, 'ref_row_number': 1,
            'product_id': 1, 'tax_ratio': 13.0,
            'quantity': 0.0, 'amount_untaxed': -128.72, 'amount_tax': -16.73, 'amount_total': -145.45,
            'price_untax': 0.0, 'price_unit': 0.0}),
        (0, False, {
            'line_type': 'line', 'row_number_check': 3, 'row_number': 3, 'ref_row_number': 3,
            'product_id': 2, 'tax_ratio': 6.0,
            'quantity': 1.0, 'amount_untaxed': 5.66, 'amount_tax': 0.34, 'amount_total': 6.0,
            'price_untax': 5.66037736, 'price_unit': 6.0
        })],
    'state': 'done'}
